<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <div>
    <!-- @close="handleSuccess" -->
    <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      @register="registerDrawer"
      :title="getTitle.value"
      width="90%">
      <template #title>
        <Icon :icon="getTitle.icon" class="pr-1 m-1" />
        <span> {{ getTitle.value }} </span>
        <div>  仓库:<b>{{ cwhcode }}</b></div>
      </template>
        <!-- {{ tabsFormSchema }} -->
      <a-affix :offset-top="top">
        <Tabs v-model:activeKey="activeKey" @change="tabchange" type="card">
          <Tabs.TabPane
            v-for="(item, index) in tabsFormSchema"
            :key="item.key"
            v-bind="omit(item, ['Table', 'key'])"
          />
        </Tabs>
      </a-affix>
      <BasicTable @register="registerTableColumn" class="mt-10" :sticky="true">
        <template #field="{ record, column }">
          
          <div @click="handleSelectPos(record, column)"  :class="{ 
            'bg-blue-500': handleDataIndex(record, column)['selected'] || ( handleDataIndex(record, column)['selected'] && handleDataIndex(record, column)['binv'] === '1' ), 
            'bg-red-500': handleDataIndex(record, column)['binv'] === '1' && !handleDataIndex(record, column)['selected'] }" style="cursor: pointer;" >
                {{ handleDataIndex(record, column)['cposcode'] && handleDataIndex(record, column)['cposcode'] }}
          </div>
        </template>
      </BasicTable>
      <template #footer>
        <div class="flex justify-between align-middle items-center">
          <div>选中货位: <b>{{ selectedPos.cposname && selectedPos.cposcode ? selectedPos.cposname + '-' + selectedPos.cposcode : '' }}</b></div>
          <a-button type="primary" @click="handleSubmit"> 确定 </a-button>
        </div>
      </template>
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ListPos',
    inheritAttrs: false,
  });
</script>
<script lang="ts" setup>
  import { ref, unref, nextTick, defineComponent } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tabs } from 'ant-design-vue';
  import { router } from '/@/router';
  import { useMessage, showMessageModal, showMessage, createWarningModal, createConfirm } from '/@/hooks/web/useMessage';
  import { omit } from 'lodash-es';
  import { findPosTop, findPosRowByOne } from '/@/api/bas/findPos';
  import { whTmShSavePos } from '/@/api/wh/sh/whTmSh';
  import { PageWrapper } from '/@/components/Page';
  import { BasicModal, useModal } from '/@/components/Modal';
  const { meta } = unref(router.currentRoute);
  const emit = defineEmits(['success', 'register']);
  const tabsFormSchema = ref([]);
  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: router.currentRoute.value.query.tabTitle || '指定货位',
  };
  const { showMessage, showMessageModal, createWarningModal ,createConfirm} = useMessage();
  const activeKey = ref('01');
  const cwhcode = ref('');
  const dataSource = ref([]);
  const selectedPos = ref({});
  const taskId = ref('');
  const tableColumns: BasicColumn[] = [];
  const registerTableColumn = ref(useTable());
  // dictType
  const { t } = useI18n('bas.inv.basInv');
  const top = ref<number>(102);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data: any) => {
    setDrawerProps({ loading: true });
    selectedPos.value = {};
    tabsFormSchema.value = [];
    // tableColumns = [];
    // 重置tableColumns 为空数组
    tableColumns.length = 0;
    cwhcode.value = data.cwhcode;
    taskId.value = data.id;
    console.log('activeKey', activeKey.value);

    await handleTabsFormSchema();
    await nextTick();
    setDrawerProps({ loading: false });
  });
  async function handleSubmit() {
    if (!selectedPos.value.cposcode) {
      showMessage('请选择货位');
      return;
    }
    const res = await whTmShSavePos({
      cposcode: selectedPos.value.cposcode,
      id: taskId.value,
      status: '3',
    });
    if (res.result === 'true') {
      showMessage('指定货位成功');
      setTimeout(closeDrawer);
      emit('success', true);
    } else {
      showMessage('指定货位失败');
    }
  }

  async function handleSelectPos(record, column) {
    // if (record[column['dataIndex']].binv === '1') {
    //   // createMessage.error('该货位为不可用货位');
    //   showMessage('该货位为不可用货位');
    //   return;
    // }
    if (handleDataIndex(record, column)['binv'] === '1') {
      // createWarningModal({ content: '请确认使用该货位' })
      createConfirm({
        title: t('提示'),
        content: t(
          '请确认使用该货位',
        ),
        iconType: 'warning',
        onOk: async (_res) => {
          try {
            // const res = await bpmRollback({ id: taskRef.value.id });
            // showMessageModal({ content: res.message });
            // success();
            dataSource.value.forEach((item) => {
            // 清空选中状态
              Object.keys(item).forEach((key,index) => {
                // item[key].selected = false;
                // console.log('key', key, index);
                // item[key] 为对象
                const keyObj = Object.keys(item[key])[0];
                // console.log('keyObj', item[key][keyObj]);
                // 如何item[key][keyObj]不为空对象，则清空选中状态
                if (item[key][keyObj] !== undefined && item[key][keyObj] !== {}) {
                  item[key][keyObj]['selected'] = false;
                }
              });
            });
            record.forEach((item) => {
              Object.keys(item).forEach((key,index) => {
                if(key === column['dataIndex']) {
                  item[key]['selected'] = true;
                  selectedPos.value = {
                    cposname: item[key]['cposname'],
                    cposcode: item[key]['cposcode'],
                    id: item[key]['id'],
                  };
                  console.log('selectedPos.value', selectedPos.value);
                }
              })
            })

          } catch (error: any) {
            console.log('error', error);
          }
          return Promise.resolve();
        },
      });
      
      // showMessage('该货位为不可用货位');
      // return;
    }else{
      dataSource.value.forEach((item) => {
      // 清空选中状态
        Object.keys(item).forEach((key,index) => {
          // item[key].selected = false;
          // console.log('key', key, index);
          // item[key] 为对象
          const keyObj = Object.keys(item[key])[0];
          // console.log('keyObj', item[key][keyObj]);
          // 如何item[key][keyObj]不为空对象，则清空选中状态
          if (item[key][keyObj] !== undefined && item[key][keyObj] !== {}) {
            item[key][keyObj]['selected'] = false;
          }
        });
      });
      
      record.forEach((item) => {
        Object.keys(item).forEach((key,index) => {
          if(key === column['dataIndex']) {
            item[key]['selected'] = true;
            selectedPos.value = {
              cposname: item[key]['cposname'],
              cposcode: item[key]['cposcode'],
              id: item[key]['id'],
            };
            console.log('selectedPos.value', selectedPos.value);
          }
        })
      })


    }
    
  }

  async function handlePageChange(page: number, pageSize: number) {
    console.log('page', page, pageSize);
    const start = (page - 1) * (pageSize / 10);
    const end = start + pageSize / 10;
    console.log('dataSource.value', dataSource.value, start, end);
    let dataSourceValue = dataSource.value;
    dataSourceValue = dataSourceValue.slice(start, end);
    // const activeParenttabsFormSchema = tabsFormSchema.value.find(
    //   (item) => item.key === activeKey.value,
    // );
  }

  async function tabchange(key) {
    console.log('key', key);
    setDrawerProps({ loading: true });
    await nextTick();
    dataSource.value = [];
    tableColumns.length = 0;
    activeKey.value = key;
    await handleTable();
    setDrawerProps({ loading: false });
  }
  async function handleTabsFormSchema() {
    const res = await findPosTop({ cwhcode: cwhcode.value,bshelf: '1' });
    if (res.result == 'true') {
      const tab = res.data;
      tab.forEach(async (item, index) => {
        tabsFormSchema.value.push({
          key: item.cposcode,
          tab: item.cposname,
          forceRender: true,
        });
      });
    }
    // 默认第一条数据
    activeKey.value = res.data[0].id;
    await handleTable();
    // dataSource 取100条
    // const dataSourceValue = dataSource.value.slice(currentPage.value, (pageSize.value / 10));
  }

  async function handleTable() {
    const posRowByOne = await findPosRowByOne({ 'parent.cposcode': activeKey.value });
    if (posRowByOne.result !== 'true') {
      console.error('Failed to fetch data');
      return;
    }
    const dataSourceValue = [];
    posRowByOne.data.forEach((item) => {
      tableColumns.push({
        title: item.parent.cposcode,
        dataIndex: item.parent.cposcode,
        width: 300,
        slot: 'field',
      });
      item.list.forEach((items) => {
        // 如果item.parent.cposcode 发生变化，不清空dataSourceValue的值，但是
        if(item.parent.cposcode === items.parentCode) {
          dataSourceValue.push({
            [item.parent.cposcode]: {
              cposname: items.cposname,
              cposcode: items.cposcode,
              binv: items.binv,
              selected: false,
            },
          });
        }
      });
      dataSource.value = handleServerData(dataSourceValue);
    });
    // const FindTable = tabsFormSchema.value.find(item => item.key === activeKey.value);
    // console.log('tableColumns', FindTable, dataSourceValue);
    // console.log('tableColumns', tableColumns);
    if (registerTableColumn.value) {
      const [register, tableMethods] = registerTableColumn.value;

      tableMethods.setProps({
        columns: tableColumns,
        dataSource: dataSource.value,
        pagination: false,
      });
    } else {
      console.error('Table methods are not available');
    }
  }

  const handleDataIndex = (record, column) => {
    const tdName = record.find(item => item[column['dataIndex']]);
    if (!record || !tdName) {
      console.error('Record or column data is undefined or null');
      return ''; // or handle the error as appropriate
    }
    if (Object.keys(tdName).length > 0) {
      return tdName[[column['dataIndex']]];
    }
    return '';
  };

  const handleServerData = (list) => {
    const keys = [...new Set(list.map(item => Object.keys(item)[0]))];
// 将 list 按 key 分组
    const groupedByKey = keys.map(key => list.filter(item => item[key]));
    // 计算最大分组数
    const maxGroupCount = Math.max(...groupedByKey.map(group => group.length));
    // 构造最终的分组结果
    const result = Array.from({ length: maxGroupCount }, (_, index) => {
      return keys.map(key => {
        const group = groupedByKey.find(g => g[0] && Object.keys(g[0])[0] === key);
        return group && group[index] ? group[index] : { [key]: {} };
      });
    });
    return result;

  };
  // Define the structure of each tab item
</script>
<style scoped>
  .ant-tabs-nav-wrap {
    flex-wrap: wrap; /* 允许子元素换行 */
  }

  .ant-tabs-tab {
    white-space: nowrap; /* 防止标签内的文字断行 */
  }
  ::v-deep(.ant-table-sticky-scroll) {
    position: fixed !important;
    bottom: 60px !important;
  }

  .custom-scroll-container {
    overflow-x: auto;
    padding-top: 500px; /* Adjust based on your table height */
    margin-top: -500px; /* Negative margin to offset the padding */
  }
</style>
